<template>
  <div class="app-container">
    <el-row :gutter="10" class="search-top">
      <el-col :span="1.5">
        <el-row>
          <el-col>
              <el-page-header @back="backTo" title="" :content="taskInfo.taskType"/>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="1.5" style="float: right;">
        <el-button style="margin-left: 20px;"
                   type="primary"
                   plain
                   icon="el-icon-download"
                   size="mini"
        >下载日志</el-button>
      </el-col>
      <el-col :span="1.5" style="float: right;" v-if="taskInfo.taskStat==2">
        <el-tooltip placement="top">
          <div slot="content">
            1、放弃任务将回滚执行成功的步骤<br/>
            2、放弃任务后，任务累计耗时将重新计算
          </div>
          <el-popconfirm
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="确认放弃任务？"
            @confirm="rollbackTask"
          >
            <el-button style="margin-left: 20px;" slot="reference"
                       type="primary"
                       plain
                       icon="el-icon-refresh-left"
                       size="mini"
            >放弃任务</el-button>
          </el-popconfirm>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5" style="float: right;" v-if="taskInfo.taskStat==2">
        <el-tooltip placement="top">
          <div slot="content">
            1、重新发起会从失败的位置继续重新执行任务<br/>
            2、请根据失败原因进行对应处理后发起
          </div>
          <el-popconfirm
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="确认重新发起任务？"
            @confirm="retryTask"
          >
            <el-button slot="reference"
                       type="danger"
                       plain
                       icon="el-icon-refresh-right"
                       size="mini"
              >重新发起</el-button>
          </el-popconfirm>
        </el-tooltip>
      </el-col>

    </el-row>
      <el-row style='font-size: 14px;color: #48576a;font-family:"Microsoft Yahei", sans-serif;margin-bottom: 10px;'>
        <el-col :span="2">
          任务ID：{{taskInfo.id}}
        </el-col>
        <el-col :span="4">
          任务状态：
          <span v-if="taskInfo.taskStat==0">未开始</span>
          <span v-if="taskInfo.taskStat==1" style="color:green;">运行中</span>
          <span v-if="taskInfo.taskStat==2" style="color:red;">失败</span>
          <span v-if="taskInfo.taskStat==3" style="color:blue;">成功</span>
        </el-col>
        <el-col :span="4">
          当前进度：{{taskInfo.finishCnt}}/{{taskInfo.totalCnt}}
        </el-col>

        <el-col :span="4">
          任务累计耗时：{{timeCost}}
        </el-col>
        <el-col :span="4">
          开始执行时间 ：{{taskInfo.startTime}}
        </el-col>
        <el-col :span="4">
          结束时间 ：{{taskInfo.endTime}}
        </el-col>
        <el-col :span="2">
            <el-tooltip :content="scrollCurrent?'点击关闭日志滚动':'点击开启日志滚动'"
                        style="float: right;margin-right: 10px;" placement="top">
              <el-switch v-model="scrollCurrent"/>
            </el-tooltip>
        </el-col>
      </el-row>
      <el-row v-if="taskInfo.taskStat==0">
        <el-col>
          <el-card body-style='height:400px;text-align:center;padding-top:300px;font-size: 14px;color: #48576a;font-family:"Microsoft Yahei", sans-serif;'>
            当前任务尚未开始
            <!--                        点击<el-button type="text" @click="runTask()">立即执行</el-button>启动任务-->
          </el-card>
        </el-col>
      </el-row>
      <el-row v-else style='font-size: 14px;color: #48576a;font-family:"Microsoft Yahei", sans-serif;' >
        <el-col :span="6" style="max-height: 700px;border: 1px solid #e6ebf5;" class="card" v-if="taskSteps.length>0">
          <el-card body-style="overflow-y: auto;">
            <el-steps :space="100" direction="vertical">
              <el-step v-for="step in taskSteps" :key="step.id"
                       :title="step.taskType"
                       :status="calcStatus(step.taskStat)">
                <template slot="description">
                  <div @click="jumpTo(step.id)" style="cursor: pointer;" title="点击定位当前日志">
                    <div>{{step.taskDesc}}</div>
                    <div style="padding-left: 130px;">{{calcSubTaskCost(step)}}</div>
                  </div>
                </template>
              </el-step>
            </el-steps>
          </el-card>
        </el-col>
        <el-col :span="taskSteps.length>0 ? 18 : 24" style="padding-left: 5px;max-height: 700px;border: 1px solid #e6ebf5;" class="card">
          <el-card body-style="overflow-y:auto;">
            <div v-for="log in taskLog" :key="log.id" :ref="'log_'+log.taskId">
              <el-row>
                <el-col :span="3" style="text-align: center">{{log.createTime}}</el-col>
                <el-col :span="1" style="text-align: center">{{log.logLevel}}</el-col>
                <el-col :span="19" style="text-align: left">{{log.logMsg}}</el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
  </div>
</template>

<script>
import { listTask, getTask, listTaskLog, retryTask, rollbackTask } from "@/api/task/task";

export default {
  name: "Task",
  dicts:['kw_task_status'],
  data() {
    return {
      taskId:this.$route.params.taskId,
      taskInfo:{},
      taskSteps:[],
      taskLog:[],
      taskInterval:undefined,
      timeCost:"-",
      cur_task_id:0,
      scrollCurrent:true,
    };
  },
  created() {
    this.getTaskInfo()
    this.getSteps()
  },
  methods: {
    calcStatus(stat){
      switch (stat){
        case 0:
          return 'wait'
        case 1:
          return 'process'
        case 2:
          return 'error'
        case 3:
          return 'success'
          return 'finish'
      }
    },
    calcSubTaskCost(task){
      let start=task.startTime,end=task.endTime;
      if(!end) end = new Date()
      if(start){
        let sec = new Date(end)-new Date(start);
        return "开始："+start.substr(11)+" 耗时："+this.getDetaTime(end,start);
      }
      return '';
    },
    async getTaskInfo(){
      let res = await getTask(this.taskId)
      if(res.code===200){
        this.taskInfo = res.data;
        if(this.taskInfo==undefined || this.taskInfo==null || this.taskInfo==""){
          this.$modal.msgWarning("任务不存在！");
          this.backTo();
        }
        if(this.taskInfo.endTime){
          this.timeCost = this.getDetaTime(this.taskInfo.endTime,this.taskInfo.startTime)
        }else if(this.taskInfo.startTime){
          this.timeCost = this.getDetaTime(new Date(),this.taskInfo.startTime)
        }
        await this.getTaskLog();
        if(this.taskInfo.taskStat==1){
          this.taskInterval = setTimeout(this.refreshPage,1000);
          if(this.scrollCurrent){
            this.jumpTo(this.cur_task_id)
          }
        }
      }
    },
    async refreshPage(){
      await this.getTaskInfo();
      await this.getSteps();
    },
    async getSteps() {
      let res = await listTask({'pId':this.taskId})
      if(res.code===200){
        this.taskSteps = res.rows;
      }
    },
    async getTaskLog(){
      let param = {'pId':this.taskInfo.id}
      if(this.taskLog.length>0){
        param['id']=this.taskLog[this.taskLog.length-1].id;
      }
      let res = await listTaskLog(param);
      if(res.code===200){
        this.taskLog = this.taskLog.concat(res.rows);
      }
      if(this.taskLog.length>0){
        this.cur_task_id = this.taskLog[this.taskLog.length-1].taskId;
      }
    },
    getDetaTime(end,start){
      let sec = parseInt((new Date(end)-new Date(start))/1000);
      if(sec<60){
        return sec+"秒"
      }else if(sec<60*60){
        let min = parseInt(sec/60);
        return min+"分"+(sec%60)+"秒"
      }else if(sec<60*60*24){
        let hour = parseInt(sec/60/60);
        let min = parseInt((sec-60*60*hour)/60);
        return hour+"小时"+min+"分";
      }else{
        return sec+"秒"
      }
    },

    backTo(){
      this.$router.push({
        path: "/system/task",
      });
    },
    jumpTo(taskId){
      let ele = this.$refs['log_'+taskId];
      if(ele){
        ele[ele.length-1].scrollIntoView(true)
      }
    },
    async rollbackTask(){
      let res = await rollbackTask(this.taskId);
      if(res.code==200){
        this.$modal.msgSuccess("放弃任务发起成功");
        this.taskInterval = setTimeout(this.refreshPage,1000);
      }
    },
    async retryTask(){
      let res = await retryTask(this.taskId);
      if(res.code==200){
        this.$modal.msgSuccess("重试任务发起成功");
        this.taskInterval = setTimeout(this.refreshPage,1000);
      }
    },

  },
  destroyed() {
    if(this.taskInterval){
      clearTimeout(this.taskInterval)
    }
  },
};
</script>
<style scoped>

.card{
  overflow-y:auto  /* 开启滚动显示溢出内容 */
}
</style>
